#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import os
import oauth
import logging
import urllib, urllib2


from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from django.utils import simplejson
from google.appengine.api import memcache
from util.InitDatabase import InitDatabase
from time import localtime
import string
import random
import ConfigParser
from signed_request import signed_request


webapp.template.register_template_library('japaneseFilter')

CONSUMER_KEY = '797623492c7530a598a8'
CONSUMER_SECRET = '9b56e122dd8c3f603cb1261e990ca27d2a661a8a'
BASE_URL = 'http://api.mixi-platform.com/os/0.8'

def get_person(user_id):
    data = memcache.get('person-%s' % user_id)
    if data is not None:
        return data

    consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
    params = {'xoauth_requestor_id': user_id,
              'format': 'json',
             }

    request = oauth.OAuthRequest.from_consumer_and_token(
                  consumer,
                  http_method='GET',
                  http_url=BASE_URL + '/people/@me/@self',
                  parameters=params,
              )
    request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, None)

    uri = '%s?%s' % (request.http_url, urllib.urlencode(params))
    r = urllib2.Request(uri, headers=request.to_header())

    try:
        data = simplejson.loads(urllib2.urlopen(r).read())
        memcache.add('person-%s' % user_id, data, 3600)
        return data
    except urllib2.HTTPError, e:
        logging.error(e)
        return False
    except:
        return False

        


class PlayGame(webapp.RequestHandler):
    def __init__(self):
        #MAX_NUM less than MAX_VALUE
        self.QUESTION_MAX_NUM = 4
        self.QUESTION_MAX_VALUE = 4
        self.SESSION_ID_LENGTH = 8
        self.URL_SETTING_FILE="urlSettings.ini"
        self.MOBILE_TYPE='mobile'
        self.PC_TYPE='pc'
        self.SMARTPHONE_TYPE='smartphone'
        
            
    def get(self):
        # set questin number 0
        # return html
        self.response.headers['Content-Type'] = 'application/xhtml+xml; charset=Shift_JIS'
        conf = self.getURLConfiguration()
        supportBrowser=checkBrowser(self.request.user_agent)
        userAgent=detectAgent(self.request.user_agent)
        if supportBrowser==False:
                template_values={}
                if userAgent == 'android2.1':
                    self.response.headers['Content-Type'] = 'application/xhtml+xml; charset=UTF-8'
                    path = os.path.join(os.path.dirname(__file__), './tmpl/notsupport_u.html')
                else:
                    template_values = {
                        'userAgent': userAgent,
                        'supportBrowserURL':conf.get(userAgent,'supportBrowserURL'),
                    }
                    path = os.path.join(os.path.dirname(__file__), './tmpl/notsupport_o.html')
                self.response.out.write(template.render(path, template_values))

        else:
            
            ownerID = self.request.get('opensocial_owner_id')
            person=self.getUserInfo(ownerID)
            if person is not None:
                username = person['entry']['nickname']
     
            if self.checkPlayed(username):
       
                template_values = {
                                   'message': u'今日はすでに診断したのでまた明日遊んでね',
                                   }
                path = os.path.join(os.path.dirname(__file__), './tmpl/message_o.html')
                self.response.out.write(template.render(path, template_values))
            else:
            
                if username =='':
                    username = 'anonymous'
                sessionID = ownerID + self.createSessionID()
        
                template_values = {
                               'question_num': '0',
                               'session_id': sessionID,
                               'username':username,
                               'cssURL':conf.get(userAgent,'cssURL'),
                               'gameURL':conf.get(userAgent,'gameURL'),
                               'privacyURL':conf.get(userAgent,'privacyURL'),
#                               'userAgent':self.request.user_agent,
                               'userAgent':userAgent,
                               'userAgentFull':self.request.user_agent,
                               'utilJSURL':conf.get(userAgent,'utilJSURL'),
                               'appliTitle':conf.get(userAgent,'appliTitle'),
                               'supportBrowserURL':conf.get(userAgent,'supportBrowserURL'),
                               'imgRootURL':conf.get(userAgent,'imgRootURL'),
                               'appRootURL':conf.get(userAgent,'appRootURL'),
                               }
                path = os.path.join(os.path.dirname(__file__), './tmpl/top_o.html')
                self.response.out.write(template.render(path, template_values))
    
    def checkPlayed(self,nickname):
        player=memcache.get('player')  
        if player == nickname:
            return True
        else :
            return False
        
    def setDayPlayLimitation(self,nickname): 
        times = localtime()
        lastMinutes = (23-times[3])*3600+(59-times[4])*60+(59-times[5])
        #memcache.add('player',nickname,lastMinutes)
        memcache.add('player',nickname,30)
        
    def getURLs(self,settingFile):
        conf = ConfigParser.SafeConfigParser()
        conf.read(settingFile)
        return conf
        

    def getUserInfo(self, user_id):
  #      data = memcache.get('person-%s' % user_id)
  #      if data is not None:
  #          return data

        consumer = oauth.OAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET)
        params = {'xoauth_requestor_id': user_id,
                  'format': 'json',
                  }

        request = oauth.OAuthRequest.from_consumer_and_token(
                  consumer,
                  http_method='GET',
                  http_url=BASE_URL + '/people/@me/@self',
                  parameters=params,
              )
        
        request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, None)

        uri = '%s?%s' % (request.http_url, urllib.urlencode(params))
        r = urllib2.Request(uri, headers=request.to_header())

        try:
            data = simplejson.loads(urllib2.urlopen(r).read())
   #         memcache.add('person-%s' % user_id, data, 3600)
            return data
        except urllib2.HTTPError, e:
            logging.error(e)
            return False
        except:
            return False
        
    
    def createSessionID(self):
        chars = string.ascii_letters + string.digits + '_'
        sessionID = "".join([ random.choice(chars) for i in range(self.SESSION_ID_LENGTH) ])
        return sessionID
    
     
    def post(self):
        userAgent=detectAgent(self.request.user_agent)
        if userAgent != 'pc':
            self.request.charset="Shift-JIS"
            
        gender = self.request.get("gender")
        sessionID = self.request.get("sessionID")
        questionNumStr = self.request.get("questionNum")
        username = self.request.get("username")
        nickname = self.request.get("nickname")
        questionID=self.request.get("questionID")
        answer = self.request.get("answer")

        questionNum = int(questionNumStr)
        if questionNum ==0 :
            memcache.add('person-%s' % sessionID,nickname,300)
            questionIDList = self.createRandomList(self.QUESTION_MAX_NUM, self.QUESTION_MAX_VALUE)
            self.setQuestions(questionIDList, sessionID,gender)
        else:
            self.storeAnswer(questionNum,answer,sessionID)
            
        if questionNum >= self.QUESTION_MAX_NUM:
            self.finalizeGame(sessionID, gender, username,nickname)
        
        else :
            self.retrieveQuestion(sessionID, questionNum, gender, username,nickname)     
     
    def setQuestions(self, questionIDList, cacheKey,gender):
        i = 0
        questionsList = []
        for qID in questionIDList:
            questions = db.GqlQuery("SELECT * FROM Quiz WHERE questionID= :1 AND type = :2", str(qID),int(gender))
            for question in questions:
                questionsList.append(question)
        
        # Store the questionList to memcache with key is userID+sessionID and value is questionList for 5 minutes
        memcache.add(cacheKey, questionsList, 300)

    def storeAnswer(self, questionNum,answer,sessionID):
        answerList = memcache.get('answer-%s' % sessionID)
        if answerList is None:
            answerList=[]
            for i in range(self.QUESTION_MAX_NUM):
                answerList.append("0")
        answerList[questionNum-1]=answer
        memcache.set('answer-%s' % sessionID,answerList,180)

    def getURLConfiguration(self):
        conf = memcache.get('confURL')
        if conf is None:
            conf = self.getURLs(self.URL_SETTING_FILE)
            memcache.add('confURL',conf,60)
        return conf

    def retrieveQuestion(self, sessionID, questionNum, gender, username,nickname):
        questionList = memcache.get(sessionID)
        question = questionList[questionNum]
        
        conf = self.getURLConfiguration()
        userAgent=detectAgent(self.request.user_agent)
        
        ###
        questionNum = questionNum + 1
        self.response.headers['Content-Type'] = 'application/xhtml+xml; charset=Shift_JIS'
        template_values = {
            'question' : question,
            'questionNum': questionNum,
            'sessionID' : sessionID,
            'gender' : gender,
            'cssURL':conf.get(userAgent,'cssURL'),
            'gameURL':conf.get(userAgent,'gameURL'),
            'userAgent':userAgent,
            'username':username,
            'nickname':nickname,
            'utilJSURL':conf.get(userAgent,'utilJSURL'),
            'imgRootURL':conf.get(userAgent,'imgRootURL'),
            'appRootURL':conf.get(userAgent,'appRootURL'),
        }
        path = os.path.join(os.path.dirname(__file__), 'tmpl/game_o.html')
 
        self.response.out.write(template.render(path, template_values))

    def finalizeGame(self, sessionID, gender, username, nickname):

        gen = "0"
        if gender == "1" :
            gen = "1"
        point = self.checkAnswers(sessionID)
        level = self.checkLevel(point)
        
        
        # check an existence of the diagnosis in memcach, if this is first time add the data to memcache
#        diagnosis=memcache.get('diagnosis-%s' % str(level))
#        if diagnosis is None:
        diagnoses = db.GqlQuery("SELECT * FROM Diagnosis WHERE levelID = :1 AND gender = :2", level, gen)
        diagnosis = diagnoses.fetch(1)
#            memcache.add('diagnosis-%s' % str(level), diagnosis, 30)
        
        # check an existence of the luckyitem in memcach, if this is first time add the data to memcache        
      
        
        nickname2=memcache.get('person-%s' % sessionID)
        if nickname2 is None:
            nickname2 ='anonymous'
 
        conf = self.getURLConfiguration()
        userAgent=detectAgent(self.request.user_agent)
        
        postText=''
        if diagnosis[0].title is not None:
            title=diagnosis[0].title
        else:
            title=""
        
#        ownerID = self.request.get('opensocial_owner_id')
#        person=self.getUserInfo(ownerID)
#        if person is not None:
#            username = person['entry']['nickname']
       
        postText = unicode(username) + u'さんの気になる'+unicode(nickname2) + u'さんの草食度は'+title+u"レベルです"
        ###
        
        ### self.setDayPlayLimitation(username) #limitation for play once a day
            
        self.response.headers['Content-Type'] = 'application/xhtml+xml; charset=Shift_JIS'
        template_values = {
            'ratio':point*5,
            'diagnosisText': diagnosis[0].diagnosisText,
            'diagnosisTitle': title,
            'nickname' : nickname2,
            'cssURL':conf.get(userAgent,'cssURL'),
            'voiceURL' : conf.get(userAgent,'voiceURL'),
            'inviteURL' :conf.get(userAgent,'inviteURL'),
            'appliURL':conf.get(userAgent,'appliURL'),
            'gameURL':conf.get(userAgent,'gameURL'),
            'utilJSURL':conf.get(userAgent,'utilJSURL'),
            'postText': postText,
            'userAgent':userAgent,
            'imgRootURL':conf.get(userAgent,'imgRootURL'),
            'appRootURL':conf.get(userAgent,'appRootURL'),

        }
        path = os.path.join(os.path.dirname(__file__), 'tmpl/result_o.html')
        self.response.out.write(template.render(path, template_values))

    def checkAnswers(self,sessionID):
        answerList = memcache.get('answer-%s' % sessionID)
        if answerList is None:
            return 0
        else:
            i=0
            questionList = memcache.get(sessionID)
            totalPoint=0
            if questionList is None:
                return 0
            else:
                for answer in answerList:
                    question = questionList[i]
                    pointList = question.points
                    point = pointList[int(answer)]
                    i=i+1
                    totalPoint = totalPoint+ point
                return totalPoint
                
        
    def checkLevel(self,number):
        levels=[20,16,11,6,0]
#        levels=[0,21,42,64,83,99,120]
        for x in range(len(levels)):
            if number >= levels[x]:
                return len(levels)-x
            
        
    def createRandomList(self, elementMaxNum, elementMaxValue):
        randomNumList = []
        i = 0
        while i < elementMaxNum:
            qid = random.randint(0, elementMaxValue - 1)
            if qid not in randomNumList:
                randomNumList.append(qid)
                i += 1
        return randomNumList
           
class PrivacyPolicy(webapp.RequestHandler):   
            
    def get(self):
        template_values = {}
        self.response.headers['Content-Type'] = 'application/xhtml+xml; charset=Shift_JIS'
        path = os.path.join(os.path.dirname(__file__), 'tmpl/privacy_o.html')
        self.response.out.write(template.render(path, template_values))

class SupportBrowser(webapp.RequestHandler):   
            
    def get(self):
        template_values = {}
        self.response.headers['Content-Type'] = 'application/xhtml+xml; charset=Shift_JIS'
        path = os.path.join(os.path.dirname(__file__), 'tmpl/supportBrowser_o.html')
        self.response.out.write(template.render(path, template_values))

   
application = webapp.WSGIApplication([
        ('/game', PlayGame), ('/dbutil', InitDatabase), ('/privacy', PrivacyPolicy), ('/browser', SupportBrowser)], debug=True)


def detectAgent(userAgent):
    if userAgent.startswith('DoCoMo'):
        return 'mobile'  
    elif userAgent.startswith('KDDI-'):
        return 'mobile'
    elif userAgent.startswith('SoftBank'):
        return 'mobile'
    elif userAgent.startswith('Vodafone'):
        return 'mobile'
    elif userAgent.startswith('Mozilla/5.0 (Linux; U; Android 2.1'):
        return 'android2.1'
    elif userAgent.startswith('Mozilla/5.0 (iP'):
        return 'smartphone'
    elif userAgent.startswith('Mozilla/5.0 (Li'):
        return 'smartphone'
    else:
        return 'pc'

def checkBrowser(userAgent):
    if userAgent.startswith('Mozilla/5.0 (Linux; U; Android 2.1'):
        return False
    elif userAgent.startswith('Mozilla/5.0 (compatible; MSIE 9.0'):
        return False
    else:
        return True

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()
